<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Albert <albert_p@foxmail.com>
// +----------------------------------------------------------------------
$id = 0;
global $files;
$files = [];
$dir   = function () {
    yield __DIR__ . "/app";
    yield __DIR__ . "/config";
};

function read($dir)
{
    global $files;
    $resource = opendir($dir);
    while (($file = readdir($resource)) !== false) {
        if ($file != "" && $file != "." && $file != "..") {
            $file = $dir . "/" . $file;
            if (is_file($file)) {
                $files[] = [
                    'file' => $file,
                    'time' => stat($file)['mtime']
                ];
            } else if (is_dir($file)) {
                read($file);
            }
        }
    }
}

function inotify(): bool
{
    global $files;
    foreach ($files as $key => $item) {
        if (is_file($item['file'])) {
            $mtime = stat($item['file'])['mtime'];
            if ($mtime > $item['time']) {
                $files[$key]['time'] = $mtime;
                return true;
            }
        }
    }
    return false;
}

foreach ($dir() as $key => $item) {
    read($item);
}

$create = function () {
    $process = new \swoole_process(function ($worker) {
        $worker->exec("/usr/local/bin/php71", [__DIR__ . '/jy', "server:http", "dev"]);
    }, false, false);
    return $process->start();
};

$id = $create();
while (true) {
    clearstatcache();
    sleep(2);
    if (inotify() === true) {
        if ($id > 0) {
            \swoole_process::kill($id);
            \swoole_process::wait();
            echo "重启成功";
        }
        $id = $create();
    }
}